package cn.wolfcode.trip.base.filter;

import cn.wolfcode.trip.base.util.UploadUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

//图片过滤器,只对/upload开头的资源起过滤作用
@WebFilter("/upload/*")
public class ImageFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // http://localhost/upload/bunny.jpg
        String uri = req.getRequestURI();
        // bunny.jpg
        String filename = uri.substring(uri.lastIndexOf('/') + 1);
        // d:/upload/bunny.jpg
        Path path = Paths.get(UploadUtil.imgDir, filename);
        if (Files.exists(path)) {
            resp.setContentType("image");
            Files.copy(path, response.getOutputStream());
        } else {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {}

    public void destroy() {}
}
